#!/usr/bin/env python
#coding=utf-8
import os, sys
import glob
import fnmatch
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
import matplotlib.dates as mdate
import datetime
from matplotlib.font_manager import FontProperties  # 导入FontProperties

######################################
# 使用方法：
# python plot_temp temp_data_dir
######################################

def get_timestamp(date):
    return datetime.datetime.strptime(date,"%Y-%m-%d %H:%M:%S").timestamp()

# 设置中文字体显示
font = None

if sys.platform.startswith('darwin'):
    font = FontProperties(fname="/Users/xyh/.local/share/SimHei.ttf", size=14)  # 设置字体
elif sys.platform.startswith('linux'):
    font = FontProperties(fname="/home/xyh/.local/share/SimHei.ttf", size=14)  # 设置字体


def get_MonitorFiles(dirname):
    pattern = '*.txt'
    flist = []
    for r, d, f in os.walk(dirname):
        matches = fnmatch.filter(f, pattern)
        for m in matches:
            flist.append('{}/{}'.format(r,m))
    flist = np.unique(flist)

    if len(flist) == 0:
        raise Exception("len(flist) is zero.")

    return flist

def read_monitor_data_from_dir(dirname, delimiter='\t', encoding='utf-8'):
    flist = get_TempFiles(dirname)
    dates = []
    data = []
    cnt = 0
    for f in flist:
        print('--> loading temperature data from : {}'.format(f))
        dates_tmp, data_tmp = read_temp_data_from_file(f, delimiter=delimiter, encoding=encoding)
        for i in range(len(dates_tmp)):
            dates.append(dates_tmp[i])
            data.append(data_tmp[i])

    return np.array(dates), np.array(data)

    

def read_temp_data_from_file(temp_file, delimiter='\t', encoding='utf-8'):
    fp = open( file = temp_file, 
               mode = 'r',
               encoding = encoding)
    tags = fp.readline().split(delimiter) # NOT USED

    lines = fp.readlines()
    dates = []
    data = []
    for line in lines:
        tmp = line.split(delimiter)
        dates.append(tmp[0])
        dtmp = []
        for i in range(1,len(tmp)):
            dtmp.append(float(tmp[i]))
        data.append(dtmp)

    fp.close()
    return dates, data


def plot_temp(dates, temp, temp_idx, temp_lbs, marker_style):
    timestamp=pd.to_datetime(dates)
    fig = plt.figure(figsize=(15,6))
    ax = plt.subplot(111)
    # ax.xaxis.set_major_formatter(mdate.DateFormatter('%m/%d %H:%M:%S'))
    ax.xaxis.set_major_formatter(mdate.DateFormatter('%m-%d %H:%M')) #指定时间显示的格式
    # plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='S'), rotation=25)
#    plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='240min'), rotation=30)   #以4hrs为时钟间隔
    plt.xticks(pd.date_range(timestamp[0], timestamp[-1], freq='30min'), rotation=30)   #以4hrs为时钟间隔
    
    for idx in temp_idx:
        # ax.plot(timestamp, temp[:,idx], linestyle=line_style[idx], label=temp_lbs[idx])
        ax.plot(timestamp, temp[:,idx], marker=marker_style[idx], markersize=3, linestyle='', label=temp_lbs[idx])
    
    t173 = 173*np.ones(len(timestamp))
    t358 = 358*np.ones(len(timestamp))
    ax.plot(timestamp, t173, color='b', lw=3, linestyle='dashed', label='173K')
    ax.plot(timestamp, t358, color='r', lw=3, linestyle='dashed', label='358K')
    ax.legend(loc='best', prop=font)
    ax.set_xlabel('Dates')
    ax.set_ylabel('Temp(K)')
    ax.grid()
    
    plt.tight_layout()
    plt.show()


#################################################################################
# 这里的对应关系需要你自己再确认一遍
temp_lbs = [r'通道A-冷板1', u'通道B-冷板', u'通道C1-探测器', u'通道C2-冷板2', u'通道C3-液氮1', u'通道C4-液氮2']
temp_lbs = [r'吸附盒', u'通道B-冷板', u'冷板1', u'冷板2', u'探测器1', u'探测器2']
marker_style = ['d', 's', 'o', 'v', '^', '*']

if __name__=='__main__':
    dates, temp = read_temp_data_from_dir(sys.argv[1], encoding='iso-8859-1')
    dates = dates[::100]
    temp = temp[::100,:]
    plot_temp(dates, temp, temp_idx=temp_idx, temp_lbs=temp_lbs, marker_style=marker_style)
#    plot_temp_diff(dates, temp, temp_idx=temp_idx, temp_lbs=temp_lbs, line_style=line_style)
    
    
